const express = require("express");
const router = express.Router();
const userServ = require("../../services/userService");
const { asyncHandler } = require("../getSendResult");
const jwt = require("../jwt");
const { pick } = require("../../util/propertyHelper");

router.post(
  "/login",
  asyncHandler(async (req, res) => {
    const { code } = req.body;

    // 调用服务层处理登录逻辑
    const { user, openid } = await userServ.login(code);

    if (user) {
      // 登录成功，返回token
      jwt.publish(res, undefined, { id: user.id, openid: user.openid });
      return {
        data: user,
      }
    } else {
      // 未注册
      jwt.publish(res, undefined, { openid })
      return {
        code: 1,
        msg: 'User not found',
        data: null,
      }
    }

  })
);

router.get("/getById", asyncHandler(async (req, res) => {
  const user = await userServ.getUserById(req.userId);
  return { data: user };
}));

router.post("/register", asyncHandler(async (req, res) => {
  const { nickname, avatarUrl } = req.body;
  const { openid } = req.user;
  const user = await userServ.createUser({
    openid,
    nickname,
    avatarUrl,
  });
  return { data: user };
}));

router.post("/update", asyncHandler(async (req, res) => {
  const { nickname, avatarUrl } = req.body;
  const { id } = req.user;
  await userServ.updateUser(id, {
    nickname,
    avatarUrl,
  });
  return { data: '' };
}));

router.get("/", asyncHandler(async (req, res) => {
  const { id } = req.user;
  const user = await userServ.getUserById(id);
  const userObj = pick(user, ['id', 'nickname', 'avatarUrl']);
  return { data: userObj };
}));


module.exports = router;